package com.itboye.ihomebank.activity.electric_meter;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.bean.FeeMonthBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.ElectricMeterPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.message.common.Const;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 2018/9/26 0026.
 */

public class HistoryRechargeRecordFragment extends Fragment implements Observer {
    private SmartRefreshLayout refresh; //刷新
    private ListView recordList; //列表
    private RelativeLayout rl;

    private String start,end;
    private int type;

    private ElectricMeterPresenter presenter;
    private String uid;
    private List<FeeMonthBean> fees;

    private MyAdapter myAdapter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_activityelectricbill, null, false);
        refresh= (SmartRefreshLayout) inflate.findViewById(R.id.refresh);
        recordList= (ListView) inflate.findViewById(R.id.recordList);
        rl= (RelativeLayout) inflate.findViewById(R.id.rl);
        refresh = (SmartRefreshLayout) inflate.findViewById(R.id.refresh);
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        if (type==1){
//            rl.setBackgroundResource(R.color.black);
//        }else {
//            rl.setBackgroundResource(R.color.green);
//        }

        fees=new ArrayList<>();
        uid= SPUtils.get(getActivity(),null, SPContants.USER_ID,"")+"";
        presenter=new ElectricMeterPresenter(this);
        myAdapter=new MyAdapter(getActivity(),fees);

        recordList.setAdapter(myAdapter);
        Calendar instance = Calendar.getInstance();
        int year = instance.get(Calendar.YEAR);
        SimpleDateFormat format = new SimpleDateFormat("MM");
        start=year+""+format.format(new Date(System.currentTimeMillis()));
        end =year+""+format.format(new Date(System.currentTimeMillis()));
        Log.d("======",start+"=="+end);
        caozuo();
    }

    //添加 type
    public void addType(int type) {
        this.type=type;
//        presenter.feeMonth(uid,start,end,"0");
    }


    @Override
    public void update(Observable o, Object arg) {

        ResultEntity entity= (ResultEntity) arg;
        if (entity!=null){

            if (entity.getEventType()==ElectricMeterPresenter.BY_Emeter_feeMonth_success){
                refresh.finishRefresh();
                if (fees.size()>0){
                    fees.clear();
                }
                List<FeeMonthBean> list= (List<FeeMonthBean>) entity.getData();
                fees.addAll(list);
                myAdapter.addData(fees);

            }else if (entity.getEventType()==ElectricMeterPresenter.BY_Emeter_feeMonth_fail){
                refresh.finishRefresh();
                ByAlert.alert(entity.getMsg());
            }
        }
    }


    private void caozuo(){
        refresh.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        //触发自动刷新
        refresh.autoRefresh();
        refresh.setEnableAutoLoadmore(false);//禁止加载更多
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        presenter.feeMonth(uid,start,end,"0");
                    }
                }, 0);
            }
        });
        refresh.setRefreshHeader(new MaterialHeader(getActivity()).setShowBezierWave(true));
        refresh.finishLoadmore();
    }

    //列表的adapter
    class MyAdapter extends BaseAdapter {
        Context context;
        List<FeeMonthBean> list;
       public MyAdapter(Context context, List<FeeMonthBean> list){
           this.context=context;
           this.list=list;
       }
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           MyViewHolder myViewHolder;
            if (convertView==null){
                myViewHolder=new MyViewHolder();
                convertView=LayoutInflater.from(context).inflate(R.layout.item_electric_historyandrecharge,null,false);
                myViewHolder.typeName= (TextView) convertView.findViewById(R.id.typeName);
//                myViewHolder.moneyValue = (TextView) convertView.findViewById(R.id.moneyValue);
                myViewHolder.twoRl= (RelativeLayout) convertView.findViewById(R.id.twoRl);
                myViewHolder.restMoneyName= (TextView) convertView.findViewById(R.id.restMoneyName);
                myViewHolder.restMoneyValue= (TextView) convertView.findViewById(R.id.restMoneyValue);
                myViewHolder.dateTime= (TextView) convertView.findViewById(R.id.dateTime);
                myViewHolder.electricAmount= (TextView) convertView.findViewById(R.id.electricAmount);
                myViewHolder.electricAmountValue= (TextView) convertView.findViewById(R.id.electricAmountValue);

                convertView.setTag(myViewHolder);
            }else {
                myViewHolder= (MyViewHolder) convertView.getTag();
            }

            java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");
            java.text.DecimalFormat   df1   =new   java.text.DecimalFormat("#0.00");
            FeeMonthBean feeMonthBean = list.get(position);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat format1 = new SimpleDateFormat("MM");
            String time = format.format(new Date(Long.parseLong(feeMonthBean.getStart()) * 1000));
            Log.d("=====",format1.format(new Date(Long.parseLong(feeMonthBean.getStart()) * 1000))+"");
            if (type==1){ //历史账单
                myViewHolder.twoRl.setVisibility(View.VISIBLE);
                myViewHolder.typeName.setText(Integer.parseInt(format1.format(new Date(Long.parseLong(feeMonthBean.getStart()) * 1000)))+"月份电费");
                myViewHolder.dateTime.setText(time);
                myViewHolder.restMoneyName.setText("电费");
                if (Double.parseDouble(feeMonthBean.getFee())/100<1){
                    myViewHolder.restMoneyValue.setText( df1.format(Double.parseDouble(feeMonthBean.getFee())/100));
                }else {
                    myViewHolder.restMoneyValue.setText( df.format(Double.parseDouble(feeMonthBean.getFee())/100));
                }

                myViewHolder.electricAmount.setText("所用电量:");
                myViewHolder.electricAmountValue.setText(feeMonthBean.getValue_used()+"度");
            }else { //充值记录
                myViewHolder.twoRl.setVisibility(View.GONE);

                myViewHolder.typeName.setText(time);
                myViewHolder.restMoneyName.setText("充值");
                if (Double.parseDouble(feeMonthBean.getBalance_charge())/100<1){
                    myViewHolder.restMoneyValue.setText(df1.format(Double.parseDouble(feeMonthBean.getBalance_charge())/100)+"元");
                }else {
                    myViewHolder.restMoneyValue.setText(df.format(Double.parseDouble(feeMonthBean.getBalance_charge())/100)+"元");

                }
            }
            return convertView;
        }

        public void addData( List<FeeMonthBean> list){
           this.list=list;
           this.notifyDataSetChanged();
        }

        public class MyViewHolder{
           TextView typeName,//电费
//                   moneyValue,//电费数值
                   restMoneyName,//剩余电费
                   restMoneyValue,//剩余电费数值
                   dateTime, //日期
                   electricAmount, //剩余电量
                   electricAmountValue; //剩余电量数值
           RelativeLayout twoRl;
        }

    }


    //刷新 数据
    public void refreshDada(String start,String end,int type){
        this.type=type;
        this.start=start;
        this.end=end;
        presenter.feeMonth(uid,start,end,"0");

    }
}
